﻿using UnityEngine;
using System.Collections;

public class AssetBundleManager : MonoBehaviour
{
    static public AssetBundleManager ABM;

    public AssetBundle[] assetBundle;
    public static ArrayList NeedDownAssetIndex;
    public static int NeedDownLoadMegaBite = 0;    
    
    static string m_Url = "http://EPEPEPEP/";

    public static int[] m_Version = null;
    //public static bool m_IsFinishCreatFile = false;
    public static int m_NumOfFile = 0;
    public static int m_BundleCount = 0;
    public static float m_CrrProgress = 0;

    public GameObject m_EventRecieaver;
    string m_SenderMessage = "OnDownLoadComplete";

    int m_CrrBundleIndex;

    public WWW crrWWW = null;

    public static void Create()
    {
        if (ABM == null)
        {
            GameObject temp = new GameObject("AssetBundleManager");
            ABM = temp.AddComponent("AssetBundleManager") as AssetBundleManager;
            ABM.InitAssetBundle();
            GameObject.DontDestroyOnLoad(temp);

            //if (Caching.spaceFree < 10485760) //10메가 남으면 캐쉬 날림
            //    Caching.CleanCache();         

            Caching.maximumAvailableDiskSpace = 1048576000; //900메가바이트
        }
    }

    void InitAssetBundle()
    {
        if (ABM.assetBundle != null)
        {
            for(int i = 0 ; i < ABM.assetBundle.Length ; i++)
            {
                if (ABM.assetBundle[i] != null)
                    ABM.assetBundle[i].Unload(false);
            }

            ABM.assetBundle = null;
        }

        ABM.assetBundle = new AssetBundle[(int)BundleIndex.max];      
    }

    public static void InitStaticValue()
    {
        m_NumOfFile = 0;
        m_BundleCount = 0;
        m_CrrProgress = 0;
        ABM.InitAssetBundle();
    }

   
    public void LoadBundleWithCash() // 이미 케쉬됬을때 호출해야함
    {
        //if(Constants.UseUnPackaging)
        //{            
        //    for (int i = (int)BundleIndex.PPmax; i < (int)BundleIndex.max; i++)
        //    {
        //        StartCoroutine(LoadBundleNoneUseProgress(i));
        //    }            
        //}
        //else
        {            
            for (int i = 0; i < (int)BundleIndex.max; i++)
            {
                StartCoroutine(LoadBundleNoneUseProgress(i));
            }           
        }                   
    }


    public IEnumerator LoadBundleNoneUseProgress(int i)
    {
        if (ABM.assetBundle[i] == null)
        {
            int index = i;          
#if UNITY_IPHONE
            string url = m_Url + "name_i" + index + ".unity3d";      
#elif UNITY_ANDROID
            string url = m_Url + "name_a" + index + ".unity3d";           
#else
            string url = m_Url + "name" + index + ".unity3d";
#endif
            while (!Caching.ready)
            {
                yield return null;
            }
            
            using (WWW www = WWW.LoadFromCacheOrDownload(url, m_Version[i]))
            {
                yield return www;               

                ABM.assetBundle[i] = www.assetBundle;

                www.Dispose();               

                if (m_EventRecieaver != null)
                    m_EventRecieaver.SendMessage(m_SenderMessage);
            }
        }
        else
        {
            if (m_EventRecieaver != null)
                m_EventRecieaver.SendMessage(m_SenderMessage);

            yield return null;
        }            
    }
    
    
    public IEnumerator LoadBundle(int i)
    {
        if (ABM.assetBundle[i] == null)
        {
            int index = i;            
#if UNITY_IPHONE
            string url = m_Url + "name_i" + index + ".unity3d";      
#elif UNITY_ANDROID
            string url = m_Url + "name_a" + index + ".unity3d";
#else
            string url = m_Url + "name" + index + ".unity3d";
#endif
            while (!Caching.ready)
            {
                yield return null;
            }
           
            using (crrWWW = WWW.LoadFromCacheOrDownload(url, m_Version[i]))
            {
                yield return crrWWW;
                
                if (!string.IsNullOrEmpty(crrWWW.error))
                {
                    Debug.LogError("heeso -------------  " + crrWWW.error);

                    if (crrWWW.error.Contains("java.net.UnknownHostException"))
                    {
                        Debug.LogError("heeso -------------  network error");
                    }
                }

                ABM.assetBundle[i] = crrWWW.assetBundle;

                crrWWW.Dispose();
                crrWWW = null;

                if (m_EventRecieaver != null)
                    m_EventRecieaver.SendMessage(m_SenderMessage);
            }
        }
        else
        {
            if (m_EventRecieaver != null)
                m_EventRecieaver.SendMessage(m_SenderMessage);

            yield return null;
        }
    }


    static public bool IsNeedDownLoad()
    {
        NeedDownLoadMegaBite = 0;

        int goal = (int)BundleIndex.max;

        bool isNeedDownLoad = false;

        if (NeedDownAssetIndex == null)
            NeedDownAssetIndex = new ArrayList();

        NeedDownAssetIndex.Clear();

        int index = 0;
        for (int i = 0; i < goal; i++)
        {
            index = i;
            
#if UNITY_IPHONE    //이름만 위의 예외 처리
            string url = m_Url + "name_i" + index + ".unity3d";      
#elif UNITY_ANDROID
            string url = m_Url + "name_a" + index + ".unity3d";
#else
            string url = m_Url + "name" + index + ".unity3d";
#endif

            if (!Caching.IsVersionCached(url, m_Version[i]))
            {
                isNeedDownLoad = true;
                NeedDownAssetIndex.Add(i);

                NeedDownLoadMegaBite += Constants.BundleNeedMemory[i];
            }
        }

        //if (Constants.UseUnPackaging)
        //{
        //    return !m_IsFinishCreatFile;
        //}

        return isNeedDownLoad;
    }

    static public bool IsNeedDownLoadJustCheck()
    {
        NeedDownLoadMegaBite = 0;

        int goal = (int)BundleIndex.max;

        bool isNeedDownLoad = false;

        int index = 0;
        for (int i = 0; i < goal; i++)
        {
            index = i;           

#if UNITY_IPHONE    //이름만 위의 예외 처리
            string url = m_Url + "name_i" + index + ".unity3d";      
#elif UNITY_ANDROID
            string url = m_Url + "name_a" + index + ".unity3d";
#else
            string url = m_Url + "name" + index + ".unity3d";
#endif

            if (!Caching.IsVersionCached(url, m_Version[i]))
            {
                isNeedDownLoad = true;

                break;
            }
        }

        //if (Constants.UseUnPackaging)
        //{
        //    return !m_IsFinishCreatFile;
        //}

        return isNeedDownLoad;
    }


    static public AssetBundle GetBundle(int i)
    {        
        return ABM.assetBundle[i];
    }


    static public Object Load(int i, string assetName)
    {
        if (GetBundle(i) != null)               
            return GetBundle(i).Load(assetName);

        return null;
    }

    //씬컨트롤러에서 호출하지만 동작은 현재 안함
    static public void UnLoadBundle(bool force)
    {       
        //if (ABM.assetBundle != null)
        //{
        //    for (int i = 0; i < (int)BundleIndex.max; i++)
        //    {                
        //        if (ABM.assetBundle[i] != null)
        //            ABM.assetBundle[i].Unload(false);              
        //    }
        //}        
    }


  
    //static bool isCorrectVirsion = true;
    //static int AlreadyCreateNum = 0;
       

    //static public void CreatePlayerPictureToDevice()
    //{    
    //    isCorrectVirsion = true;
    //    AlreadyCreateNum = 0;
    //    m_IsFinishCreatFile = false;      

    //    ABM.StartCoroutine(ABM.PlayerPictureToDevice0());
    //}


    //public IEnumerator PlayerPictureToDevice0()
    //{
    //    yield return new WaitForSeconds(0.0f);

    //    if (m_BundleCount < (int)BundleIndex.PPmax)
    //    {
    //        Object[] tempArray = null;
    //        tempArray = GetBundle(m_BundleCount).LoadAll();

    //        SceneControler.m_UIRoot.SendMessage("UpdateUI", SendMessageOptions.DontRequireReceiver);

    //        StartCoroutine(PlayerPictureToDevice1(tempArray, 0));
    //    }
    //    else
    //    {
    //        m_IsFinishCreatFile = true;
    //        HSFile.AssetFileVirsionWrite();
    //        SceneControler.m_UIRoot.SendMessage("EndOfCreatFile", SendMessageOptions.DontRequireReceiver);
    //    }
    //}


    //public IEnumerator PlayerPictureToDevice1(Object[] tempArray, int count)
    //{
    //    yield return new WaitForSeconds(0.0f);
        
    //    if(count < tempArray.Length)
    //    {
    //        if (!isFileEX)
    //        {
    //            StartCoroutine(PlayerPictureToDevice2(tempArray, count));
    //        }
    //        else if (!isCorrectVirsion)
    //        {
    //            StartCoroutine(PlayerPictureToDevice2(tempArray, count));
    //        }
    //        else
    //        {
    //            if (AlreadyCreateNum <= m_NumOfFile)
    //            {
    //                StartCoroutine(PlayerPictureToDevice2(tempArray, count));
    //            }
    //            else
    //            {
    //                m_NumOfFile++;
    //                count++;
    //                StartCoroutine(PlayerPictureToDevice1(tempArray, count));
    //            }
    //        }
    //    }
    //    else
    //    {
    //        HSFile.AssetFileVirsionWrite();
    //        GetBundle(m_BundleCount).Unload(false);
    //        m_BundleCount++;
    //        StartCoroutine(PlayerPictureToDevice0());
    //    }

    //    m_CrrProgress = (float)count / (float)tempArray.Length;
    //}


    //public IEnumerator PlayerPictureToDevice2(Object[] tempArray, int count)
    //{
    //    yield return new WaitForSeconds(0.0f);

    //    HSFile.SaveTextureToPNG((Texture2D)tempArray[count]);
    //    m_NumOfFile++;        
    //    count++;
    //    StartCoroutine(PlayerPictureToDevice1(tempArray, count));
    //}
}